<template>
    <el-dialog class="ui-store-check-dlg" v-model="dialogVisible" top="3rem" :title="dialogTitle" ref="dialog" @opened="init" :beforeClose="beforeClose" @closed="finalThings">
        <el-form :model="submit">
        <div class="left-body">
            <el-tabs>
                <el-tab-pane v-for="(item,index) in stores" :label="item.name">
                    <div ref="elToolbar" class="co-el-toolbar">
                        <el-form :model="params[index]">
                            <div class="co-toolbar co-box-row">
                                <el-form-item label="分类:" size="default">
                                    <el-select class="co-cat-select" v-model="params[index].cat_id" style="width:110px" @change="loadGoods(index)">
                                        <el-option v-for="item in categorys" :key="item.id" :label="item.name" :value="item.id" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="条件:" size="default" >
                                    <el-input class="co-search-input" placeholder="请输入商品名称或条码" v-model="params[index].code" clearable></el-input>
                                </el-form-item>
                                <el-button type="primary" @click="loadGoods(index)">查找</el-button>
                            </div>
                        </el-form>
                    </div>
                    <el-table :data="data[index]" size="small" height="30rem">
                        <el-table-column prop="name" label="商品名称"></el-table-column>
                        <el-table-column label="库存数目" align="center"  width="150">
                            <template #default="{row}">
                                <el-input-number v-model="row.new_num" size="small" :min="0" @change="setNewSale(row, item.id)" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="num_sale" label="库存数目" align="right" width="125">
                            <template #default="{row}">
                                <div v-if="row.new_num == row.store_num">{{ row.store_num }}</div>
                                <div v-else-if="row.new_num > row.store_num">
                                    {{ row.store_num }}<span style="font-weight:bold;color:var(--el-color-danger)"> + {{ row.new_num - row.store_num }}</span>
                                </div>
                                <div v-else>
                                    {{ row.store_num }}<span style="font-weight:bold;color:var(--el-color-danger)"> - {{ row.store_num - row.new_num }}</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="sale_price" label="零售价" align="right"  width="100" :formatter="rmbFormatter"></el-table-column>
                        <el-table-column prop="sum_amount" label="盈亏" align="right"  width="100">
                            <template #default="{row}">
                                <div v-if="row.sum_amount == 0">{{ row.sum_amount }}</div>
                                <div v-else-if="row.sum_amount  > 0">
                                    <span style="font-weight:bold;color:var(--el-color-danger)" v-rmb="row.sum_amount"></span>
                                </div>
                                <div v-else>
                                    <span style="font-weight:bold;color:var(--el-color-danger)" v-rmb="row.sum_amount"></span>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="ui-pagination-ctn box-row">
                        <el-pagination
                            v-model:current-page="params[index].page" :page-size="params[index].limit" :page-sizes="[13, 50, 100, 200]"
                            layout="sizes, total, prev, pager, next" :total="total[index]" 
                            @size-change="loadGoods(index)" @current-change="loadGoods(index)"
                        ></el-pagination>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
        </el-form>
        <template #footer>
            <div class="box-row">
                <span v-if="submit.sum_amount > 0.0000999" style="line-height: 2rem; padding:0 1rem; color:var(--el-color-primary)">盈: <span v-rmb="submit.sum_amount"></span></span>
                <span v-if="submit.sum_amount < 0.0000999" style="line-height: 2rem; padding:0 1rem; color:var(--el-color-primary)">亏: <span v-rmb="Math.abs(submit.sum_amount)"></span></span>
                <span style="line-height: 2rem; padding:0 .5rem">备注:</span>
                <el-input v-model="submit.desc" style="width:300px" clearable value-on-clear="''"></el-input>
                <div style="flex:1"></div>
                <el-button size="default" type="primary" @click="onSure">确认盘点</el-button>
                <el-button size="default" type="danger" @click="onCancel">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script>
import { reactive, computed, toRefs } from 'vue-demi';
import { socket, useSocket } from '../../uiframe/services/socket';
import directives from '../../uiframe/services/directives';
import { ElMessage, ElMessageBox } from 'element-plus';
export default {
    directives,
    props:{
        q: Object,
        done: Function,
        stores: Array
    },
    setup:(props)=>{
        let selectedTotal = 0;
        const stores = props.stores, 
        onmessage = msg=>ElMessage({ type: msg.success ? 'success' : 'error', message: msg.message }),
        confirm = ()=>selectedTotal>0?ElMessageBox.confirm('还有未保存的盘点数据，确定要关闭吗？', '提示', {type: 'warning'}):Promise.resolve(),
        data = reactive({
            params:stores.map(v=>({store_id: v.id, cat_id:0, page:1, limit:13})),
            dialogVisible: true,
            dialogTitle: '库存盘点',
            dialog:null, elForm:null,
            categorys:[],
            data: stores.map(v=>[]),
            total:stores.map(v=>0),
            loading: false,
            submit:{
                check:{},
                desc:''
            }
        }),rules =[

        ],
        methods = {
            loadGoods:(i)=>{
                let params = data.params[i];
                socket.rpc('StoreComponents',params).then(res=>{
                    const store_id = params.store_id;
                    data.data[i] = res.data.data.map(v=>{
                        let s = data.submit.check;
                        if(s.hasOwnProperty(store_id) && s[store_id].hasOwnProperty(v.id)){
                            v.new_num = v.store_num  + s[store_id][v.id].num;
                            v.sum_amount = v.sale_price * s[store_id][v.id].num;
                        }else{
                            v.new_num = v.store_num;
                            v.sum_amount = 0;
                        }
                        return v;
                    });
                    data.total[i] = res.data.total;
                }).catch(res=>{
                    console.log(res);
                });
            },
            onSure:()=>{
                if(data.loading) return;
                data.loading = true;
                let goods = [];
                for(let store_id in data.submit.check){
                    let s = data.submit.check[store_id];
                    for(let goods_id in s){
                        if(s[goods_id].num != 0){
                            goods.push({store_id:parseInt(store_id), id:parseInt(goods_id), num: s[goods_id].num, price: s[goods_id].price});
                        }
                    }
                }
                if(goods.length == 0){
                    data.loading = false;
                    return;
                }
                useSocket().then(socket=>{
                    socket.rpc('store.check',{goods, desc: data.submit.desc}).then(res=>{
                        onmessage(res);
                        data.loading = false;
                        if(res.success){
                            data.dialogVisible = false;
                            props.done();
                        }
                    }).catch(res=>{
                        data.loading = false;
                    });
                });
            },
            onCancel:()=>{
                confirm().then(() => {
                    data.dialogVisible = false;
                }).catch(() => {});
            },
            init:()=>{

            },
            beforeClose:(next)=>{
                confirm().then(() => {
                    next();
                }).catch(() => {});
            },
            finalThings:()=>props.done(),
            rmbFormatter:(r,c,v)=>v.toFixed(2),
            setNewSale:(row,store_id)=>{
                let s = data.submit.check, num = row.new_num - row.store_num;

                if(num != 0){
                    if(!s.hasOwnProperty(store_id)){s[store_id] = {};}
                    if(!s[store_id].hasOwnProperty(row.id)){
                        selectedTotal ++;
                    }
                    s[store_id][row.id] = {num, price: num * row.sale_price};
                } else {
                    selectedTotal--;
                    delete s[store_id][row.id];
                }
                row.sum_amount = num * row.sale_price;
                data.submit.sum_amount = Object.values(s).reduce((a,v)=>a+Object.values(v).reduce((a1,v1)=>a1+v1.price,0),0);
            }
        };

        useSocket().then(socket=>{
            socket.rpc('category',{}).then(res=>{
                data.categorys = res.data;
                data.params.map(v=>v.cat_id = res.data[0].id);
                stores.forEach((v,i)=>methods.loadGoods(i));
            }).catch(res=>{
                console.log(res);
            });
        });
        return {
            ...toRefs(data),
            ...methods,
            rules
        }
    }
}
</script>
<style lang="scss">
.ui-store-check-dlg{
    width:60rem;max-width: 60rem;
    .el-dialog__body {
        padding: 0 1.5rem 1rem 1.5rem;
    }
}
</style>